<template>
  <div class="app-container">
    <el-form :model="searchObj" ref="queryForm" :inline="true" label-width="100px">
      <el-form-item label="查询" prop="select">
        <el-input v-model="searchObj.select" placeholder="请输入订单报表需求" clearable prefix-icon="el-icon-search"
          class="custom-input" :style="{ width: '350px' }">
          <el-tooltip slot="append" content="例如：查询2025年每月的订单数量" placement="top">
            <i class="el-icon-question"></i>
          </el-tooltip>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="showChart" :loading="loading" class="search-btn">查询</el-button>
      </el-form-item>
    </el-form>

    <el-card shadow="hover" class="chart-card">
      <div slot="header" class="chart-header">
        <span class="chart-title">{{ chartTitle }}</span>
        <el-radio-group v-model="chartType" size="small" @change="changeChartType">
          <el-radio-button label="bar">柱状图</el-radio-button>
          <el-radio-button label="line">折线图</el-radio-button>
          <el-radio-button label="pie">饼图</el-radio-button>
        </el-radio-group>
      </div>
      <div ref="chart" class="chart-container"></div>
      <div v-if="noDataAvailable" class="no-data">
        <el-empty description="暂无数据"></el-empty>
      </div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'OrderEcharts',
  data() {
    return {
      searchObj: {
        select: '查询2025年每月的订单数量'
      },
      loading: false,
      chart: null,
      chartTitle: '订单统计',
      chartType: 'bar',
      xData: [], // x轴数据
      yData: [], // y轴数据
      noDataAvailable: false
    }
  },
  mounted() {
    this.initChart();
    window.addEventListener('resize', this.resizeChart);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart);
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
  },
  methods: {
    initChart() {
      if (this.chart) {
        this.chart.dispose();
      }
      this.chart = echarts.init(this.$refs.chart);
      this.showChart();
    },

    resizeChart() {
      if (this.chart) {
        this.chart.resize();
      }
    },

    changeChartType() {
      this.renderChart();
    },

    resetQuery() {
      this.searchObj.select = '查询2025年每月的订单数量';
      this.showChart();
    },

    getOrderData() {
      this.loading = true;
      this.noDataAvailable = false;

      this.$http({
        url: this.$http.adornUrl('/order/orders/ai/orderData'),
        method: 'get',
        params: this.$http.adornParams({
          'message': this.searchObj.select,
        })
      }).then(({ data }) => {
        this.loading = false;
        if (data && data.code === 200) {
          console.log(data);
          this.yData = data.data.countList;
          this.xData = data.data.dateList;

          if (this.xData.length === 0 || this.yData.length === 0) {
            this.noDataAvailable = true;
          } else {
            this.renderChart();
          }
        } else {
          this.$message.error(data.msg || '获取数据失败');
          this.noDataAvailable = true;
        }
      }).catch(() => {
        this.loading = false;
        this.noDataAvailable = true;
        this.$message.error('获取数据失败');
      });
    },

    showChart() {
      this.getOrderData();
    },

    renderChart() {
      if (!this.chart || this.noDataAvailable) return;

      let option = {};

      if (this.chartType === 'bar' || this.chartType === 'line') {
        option = {
          title: {
            text: this.chartTitle,
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: this.xData,
            axisLabel: {
              rotate: 45
            }
          },
          yAxis: {
            type: 'value',
            minInterval: 1
          },
          series: [{
            name: '订单数量',
            type: this.chartType,
            data: this.yData,
            itemStyle: {
              color: '#409EFF'
            }
          }]
        };
      } else if (this.chartType === 'pie') {
        option = {
          title: {
            text: this.chartTitle,
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            data: this.xData
          },
          series: [{
            name: '订单数量',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: true
            },
            data: this.xData.map((item, index) => {
              return {
                name: item,
                value: this.yData[index]
              };
            })
          }]
        };
      }

      this.chart.setOption(option, true);
    }
  }
}
</script>

<style scoped>
.chart-card {
  margin-top: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.chart-container {
  width: 100%;
  height: 500px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.chart-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}

.custom-input {
  transition: all 0.3s;
  border-radius: 4px;
}

.custom-input:hover,
.custom-input:focus {
  box-shadow: 0 0 8px rgba(24, 141, 240, 0.3);
}

.search-btn {
  margin-right: 10px;
  padding: 10px 20px;
  transition: all 0.3s;
}

.search-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(24, 141, 240, 0.3);
}
</style>
